package main.com.cyz.DynamicArray;

import java.util.Arrays;
import java.util.Iterator;
import java.util.function.Consumer;
import java.util.stream.IntStream;

/**
 * @author fox
 * @version 1.0
 * @description 手写动态数组
 * @date 2024/5/17 9:15
 */
public class MyDynamicArray implements Iterable<Integer> {

    //已存储数据数量
    static int size = 0;
    //动态数组容量
    static int capacity = 8;
    //基础数组
    static int[] array = new int[capacity];

    public void add(int num) {
        add(size, num);
    }

    public void add(int index, int num) {

        checkAndcapacity(index);
        System.arraycopy(array, index, array, index + 1, size - index);

        array[index] = num;
        size++;
    }

//    扩容
    private void checkAndcapacity(int index) {
        if (index < 0 || index > size) {
            throw new RuntimeException("index 非法");
        }
        if (size == capacity) {
            int[] newArray = new int[capacity + (capacity) >> 1];
            System.arraycopy(array, 0, newArray, 0, size);
            array = newArray;
        }
    }

    public void showConsumer(Consumer<Integer> consumer) {
        for (int i = 0; i < size; i++) {
            consumer.accept(array[i]);
        }
    }


    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {

            int index = 0;

            @Override
            public boolean hasNext() {
                return index < size;
            }

            @Override
            public Integer next() {
                return array[index++];
            }
        };
    }

    public IntStream showIntStream() {
        return IntStream.of(Arrays.copyOfRange(array, 0, size));
    }

    public int get(int index) {
        checkAndcapacity(index);
        return array[index];
    }

    public void remove(int index) {
        checkAndcapacity(index);
        System.arraycopy(array,index + 1,array,index,size - index);
        size --;
    }
}
